package com.dragons.dragonsvf.controller.verification_code;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author dragons
 * @version 1.0.0
 * @description:
 *      使用 Kaptcha 生成随机的图形验证码 提供给用户验证
 *      需要添加配置类  KaptchaConfig
 * @date 2025/4/29 15:43
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private CaptchaService captchaService;

    @GetMapping("/image")
    public void getImageCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 清除浏览器缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 创建验证码文本
        String capText = kaptchaProducer.createText();

        // 获取会话ID
        String sessionId = request.getSession().getId();

        // 存储验证码
        captchaService.storeCaptcha(sessionId, capText);

        // 创建验证码图片
        BufferedImage image = kaptchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();

        // 输出图片
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }



//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
//        // 获取会话ID
//        String sessionId = request.getSession().getId();
//
//        // 验证验证码
//        if (!captchaService.validateCaptcha(sessionId, loginRequest.getCaptcha())) {
//            return ResponseEntity.badRequest().body(new ApiResponse(false, "验证码错误或已过期"));
//        }
//
//        // 用户名密码验证
//        boolean authenticated = userService.authenticate(
//                loginRequest.getUsername(),
//                loginRequest.getPassword());
//
//        if (authenticated) {
//            // 生成Token或设置会话
//            String token = jwtTokenProvider.generateToken(loginRequest.getUsername());
//            return ResponseEntity.ok(new JwtAuthResponse(token));
//        } else {
//            return ResponseEntity.badRequest().body(new ApiResponse(false, "用户名或密码错误"));
//        }
//    }
}
